﻿package com.util
{
	
import flash.display.Sprite;
import flash.events.*;
import flash.system.System;
import flash.text.*;
import flash.utils.getTimer;


public class FpsMeter extends Sprite
{

	private var _textFps:TextField;
	private var _textMemory:TextField;
	public var debug:TextField;
	
	private var mfpsCount:int = 0;
	private var mfpsCount2:int = 0;
	private var avgCount:int = 30;
	private var avgCount2:int = 30;
	private var oldT:uint;
	
	private var _width:Number;
	private var _height:Number;
	
	public var threshold:Number;

	
	public function FpsMeter()
	{
		_width = 200;
		threshold = 25;

		var format:TextFormat = new TextFormat();
		format.font = 'arial';
		format.size = 11;
			
		_textFps = new TextField();
		_textFps.autoSize = "left";
		_textFps.setTextFormat( format );
		_textFps.text = "FPS average";
		_textFps.textColor = 0xffffff;
		_textFps.selectable = false;

		_height = _textFps.textHeight + 5;

		_textMemory = new TextField();
		_textMemory.text = "Memory";
		_textMemory.textColor = 0xffffff;
//		_textMemory.selectable = false;
		_textMemory.setTextFormat( format );
		_textMemory.y = 23;

		debug = new TextField();
		debug.text = "";
		debug.textColor = 0xffffff;
		debug.selectable = false;
		debug.setTextFormat( format );
		debug.y = 40;
		
		// set initial lastTime
		oldT = getTimer();
		
		addChild( _textFps );
		addChild( _textMemory );
		addChild( debug );
		
		this.mouseEnabled = false;
		this.mouseChildren = false;
	}

	
	public function update():void
	{
		var newT:uint = getTimer();
		var f1:uint = newT-oldT;
		var fps:Number = Math.round(1000/(mfpsCount/30));
		
		mfpsCount += f1;
		if (avgCount < 1){
			drawBar( fps );
			_textFps.text = String( fps )+ " FPS";
			avgCount = 30;
			mfpsCount = 0;
		}
		avgCount--;
		oldT = getTimer();
		
		_textMemory.text = Math.round(System.totalMemory/(1024*1024)) + " MB used"	
	}
	
	
	private function drawBar( fps:Number ):void
	{
		var maxFps:Number = stage.frameRate;
		var w:Number = ( fps/maxFps ) * _width;
		var color:Number = ( fps < threshold ? 0xe10000 : 0x00b000 );
		
		graphics.clear();
		graphics.beginFill( color );
		graphics.drawRect( 0, 0, w, _height );
		graphics.endFill();	
	}
	
	public function updatePhys(oldT2:uint):void
	{
		var newT:uint = getTimer();
		var f1:uint = newT-oldT2;
		mfpsCount2 += f1;
		if (avgCount2 < 1){
			_textMemory.text = String(Math.round(1000/(mfpsCount2/30))+" fps (physics)");
			avgCount2 = 30;
			mfpsCount2 = 0;
		}
		avgCount2--;
	}
	
	override public function set width( value:Number ):void
	{
		super.width = value;
		_width = value;
	}
	
	override public function set height( value:Number ):void
	{
		super.height = value;
		_height = value;
	}
}
}